<?php
/**
 * AbstractServiceRequestBroker class - 
 * Services helper class. Responsable of locate the required service according to given SERVER_URI path.
 * Ex. /services/MyService - Attemps to locate and execute the method \services\MyService.service();
 * 
 * @category	AbstractServiceRequestBroker
 * @package		application
 * @subpackage	
 * @author		Harold Roa <harold.roa@gmail.com>
 * @copyright	2009 Dayscript Ltda.
 * @license		
 * @version		1.0
 * @version		$Revision: 0 $
 * @filesource	
 * @link		http://www.dayscript.com
 * @link		{docsLink}
 * @uses		
 * @since		1.0
 * @modifiedby	$LastChangedBy: Harold Roa $
 * @modified	$Date: 2009-11-26 $
 */
namespace dayscript\application;

use	\dayscript\application\Module;
use	\dayscript\application\View;
use	\dayscript\datasource\DataSourceManager;
use	\dayscript\session\Session;
use	\dayscript\Application;
use	\dayscript\Enviroment;
use	\dayscript\event\Event;
use	\dayscript\Map;
/**
 * @author hroa
 *
 */
abstract class AbstractServiceRequestBroker extends Module	{
	const VERSION = '1.0.0.0';
		
	public function init( )	{
		$this->version = self::VERSION;		
		$this->initRequestBroker( );
		
		return true;
	}
	public abstract function initRequestBroker( );
	
	public function createListeners( )	{
		
		Application::addEventListener( $this, Event::RENDER_START, array( $this, 'onServiceRequest' ) );
		$this->createRequestBrokerListeners( );
	}
	
	public abstract function createRequestBrokerListeners( );
	
	public function dependencyCheck( )	{		
			
		return true;
	}

	public function updatesCheck( )	{
		return false;
	}	

	/**
		Service request broker method. 
	 */
	public function onServiceRequest(  Event $event  ){		
		$event->stopPropagation( );//Stops RENDER event propagation.
		
		$server_URI_parts = \explode ( "/", Enviroment::server("REQUEST_URI") );
		$base = \array_search( "services", $server_URI_parts );
				
		try{		
				
			$serviceConfig = $this->getServiceConfig( );
			$serviceConfig['module'] = $this;
			$requestedAction = FALSE;
			if( isset( $server_URI_parts[$base + 2 ] ) ){
				$method =  \explode ( "?", $server_URI_parts[$base + 2 ] );
				$requestedAction = $method[0];
			}	
			$serviceName = \explode ( "?", $server_URI_parts[$base + 1 ] );
			$reflectionClass = new \ReflectionClass( "\\services\\" . $serviceName[0] );
			$targetService = $reflectionClass->newInstanceArgs( array( $serviceConfig ) );
			$targetService->service( $requestedAction );//Las maravillas de php no hice interface ni nada.
		}catch( \Exception $classNotFoundEx ){
			echo $classNotFoundEx;
			throw new \Exception( 'Service class not found. [' . $serviceName . ']', \E_USER_ERROR );
		}		
	}	
	
	public abstract function getServiceConfig( );
}
